package muilty_thread.java_current_practice_and_kernel.cp5;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

public class BoundedHashSet<T> {
    private final Set<T> set;
    private final Semaphore sem;

    public BoundedHashSet(int bound) {
        this.set = Collections.synchronizedSet(new HashSet<>());
        this.sem = new Semaphore(bound);

    }


    public boolean add(T o) throws InterruptedException {
        sem.acquire();
        boolean add = set.add(o);
        try{
            return add;
        }finally {
            if (!add) {
                sem.release();
            }
        }


    }

    public boolean remove(Object o) throws InterruptedException {
        boolean remove = set.remove(o);
        if (remove) {
            sem.release();
        }
        return remove;

    }
}
